package com.lin.utils;


import com.lin.entity.PlaneData;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Slf4j
public class CommonUtils {
    /**
     * 获取ws连接参数值
     *
     * @param queryString
     * @param paramName
     * @return
     */
    public static String getParameter(String queryString, String paramName) {
        // topic=someTopic&extraValue=someExtraValue
        String[] split = queryString.split("&");
        for (String param : split) {
            String[] paramAndValue = param.split("=");
            if (paramAndValue.length == 2 && paramName.equals(paramAndValue[0])) return paramAndValue[1];
        }
        return null;
    }

    /**
     * 处理二进制飞机目标数据
     * id(string 15字节) code(string 4字节) lon(double 8字节) lat(double 8字节) time(long 8字节)
     *
     * @param data
     * @return
     */
    public static PlaneData processBinaryPlaneData(ByteBuffer data) {
        // id
        byte[] idBytes = new byte[18];
        data.get(idBytes);
        String id = new String(idBytes, StandardCharsets.UTF_8).trim();

        // code
        byte[] codeBytes = new byte[4];
        data.get(codeBytes);
        String code = new String(codeBytes, StandardCharsets.UTF_8).trim();

        // lon
        double lon = data.getDouble();

        // lat
        double lat = data.getDouble();

        // time
        long time = data.getLong();


//        log.info("飞机目标数据==id：{}，code：{}，lon：{}，lat：{}，time：{}", id, code, lon, lat, time);
        String[] idSplit = id.split("_");
        return new PlaneData(idSplit[0], idSplit[1], code, lon, lat, new Date(time * 1000));
    }


    /**
     * 计算两个经纬度角度
     *
     * @param oldLat
     * @param oldLon
     * @param newLat
     * @param newLon
     * @return
     */
    public static Double calculateAngle(Double oldLat, Double oldLon, Double newLat, Double newLon) {
        oldLat = oldLat * (Math.PI / 180.0);
        oldLon = oldLon * (Math.PI / 180.0);
        newLat = newLat * (Math.PI / 180.0);
        newLon = newLon * (Math.PI / 180.0);

        double dlon = newLon - oldLon;

        double y = Math.sin(dlon) * Math.cos(newLat);
        double x = Math.cos(oldLat) * Math.sin(newLat) - Math.sin(oldLat) * Math.cos(newLat) * Math.cos(dlon);


        double bearing = Math.atan2(y, x);
        bearing = bearing * (180.0 / Math.PI);
        if (bearing < 0) bearing += 360;

        return bearing;
    }

    public static Double calculateAngleOld(Double oldLat, Double oldLon, Double newLat, Double newLon) {
        double dx = newLat - oldLat;
        double dy = newLon - oldLon;

        double angle = Math.atan2(dy, dx) * (180 / Math.PI);

        if (angle < 0) angle += 360;

        return angle / 2;

    }

    public static void main(String[] args) {
        System.out.println(calculateAngle(47.4117, 45.6974, 47.4117, 45.6974));
        System.out.println("1324".getClass());
    }
}
